# Makefile for 3D Helmholtz Solvers
# Builds both FDM and FEM implementations

CC = mpicc
CFLAGS = -O3 -Wall -std=c99 -fPIC
LDFLAGS = -lm
INCLUDES = -I../inc

# Source files
FDM_SRC = helmholtz_fdm_3d.c
FEM_SRC = helmholtz_fem_3d.c
TEST_SRC = test_helmholtz_solvers.c

# Object files
FDM_OBJ = $(FDM_SRC:.c=.o)
FEM_OBJ = $(FEM_SRC:.c=.o)
TEST_OBJ = $(TEST_SRC:.c=.o)

# Executables
FDM_EXE = test_helmholtz_fdm
FEM_EXE = test_helmholtz_fem
COMBINED_EXE = test_helmholtz_solvers

# Default target
all: $(COMBINED_EXE) $(FDM_EXE) $(FEM_EXE)

# Combined test executable
$(COMBINED_EXE): $(FDM_OBJ) $(FEM_OBJ) $(TEST_OBJ)
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

# Individual executables (standalone)
$(FDM_EXE): helmholtz_fdm_3d.c
	$(CC) $(CFLAGS) $(INCLUDES) -DHELMHOLTZ_FDM_MAIN -o $@ $< $(LDFLAGS)

$(FEM_EXE): helmholtz_fem_3d.c
	$(CC) $(CFLAGS) $(INCLUDES) -DHELMHOLTZ_FEM_MAIN -o $@ $< $(LDFLAGS)

# Object file compilation
%.o: %.c
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

# Run tests
test: $(COMBINED_EXE)
	mpirun -np 1 ./$(COMBINED_EXE)

test-fdm: $(FDM_EXE)
	mpirun -np 1 ./$(FDM_EXE)

test-fem: $(FEM_EXE)
	mpirun -np 1 ./$(FEM_EXE)

# Performance test with larger problem sizes
test-performance: $(COMBINED_EXE)
	@echo "Running performance tests..."
	@echo "Small problem (32³):"
	mpirun -np 1 ./$(COMBINED_EXE)

# Clean up
clean:
	rm -f *.o $(COMBINED_EXE) $(FDM_EXE) $(FEM_EXE)

# Debug build
debug: CFLAGS += -g -DDEBUG -O0
debug: clean all

# Install (copy to bin directory)
install: $(COMBINED_EXE)
	mkdir -p ../../bin
	cp $(COMBINED_EXE) ../../bin/

.PHONY: all test test-fdm test-fem test-performance clean debug install

# Help target
help:
	@echo "Available targets:"
	@echo "  all              - Build all executables"
	@echo "  test             - Run combined tests"
	@echo "  test-fdm         - Run FDM solver test only"
	@echo "  test-fem         - Run FEM solver test only"
	@echo "  test-performance - Run performance benchmarks"
	@echo "  clean            - Remove build artifacts"
	@echo "  debug            - Build with debug symbols"
	@echo "  install          - Install to bin directory"
	@echo "  help             - Show this help message" 